package my.code.charpter5;

import java.util.ArrayDeque;
import java.util.Iterator;

/**
 * 有三个容积分别是3升、5升和8升的水桶，其中容积为8升的水桶中装满了水，容积为3升和容积为5升的水桶是空的。
 * 三个水桶都没有体积刻度，现在需要将大水桶中的8升水等分成两份，每份都是4升水，附加条件是只能使用另外两个空水桶，不能借助其他辅助容器。
 * 穷举法解
 * @author xuyuji
 *
 */
public class Main {
	
	private int i = 1;
	
	private ArrayDeque<BucketState> states = new ArrayDeque<BucketState>();
	
	public static void main(String[] args) {
		new Main().execute();
	}
	
	public void execute(){
		states.add(new BucketState(new int[]{8, 0, 0}, null));
		searchState();
	}
	
	private void searchState(){
		BucketState current = states.peekLast();
		if(current.isFinish()){
			printStates();
			return;
		}else{
			for(int i = 0; i < 3; i++){
				for(int j = 0; j < 3; j++){
					searchStateOnAction(current, i, j);
				}
			}
		}
	}
	
	private void searchStateOnAction(BucketState current, int from, int to){
		if(current.canTakeDumpAction(from, to)){
			BucketState next = new BucketState();
			current.DumpWater(from, to, next);
			if(!IsProcessedState(next)){
				states.add(next);
				searchState();
				states.pollLast();
			}
		}
	}
	
	private void printStates(){
		System.out.println(String.format("##方法%d##", i));
		for(BucketState bs : states){
			System.out.println(bs);
		}
		System.out.println(String.format("##方法%d##\n", i++));
	}
	
	private boolean IsProcessedState(BucketState next){
		Iterator<BucketState> it = states.iterator();
		while(it.hasNext()){
			BucketState bs = it.next();
			if(next.isSameState(bs)){
				return true;
			}
		}
		return false;
	}
}